{% extends "admin/admin_base.html" %}

{% block title %}API调用统计{% endblock %}
{% block breadcrumb %}API调用统计{% endblock %}

{% block content %}
<style>
/* 全局样式：直接使用具体颜色值，不依赖自定义属性 */
.container {
    padding: 20px !important;
}

/* 1. 卡片样式优化（数据统计卡片） */
.data-table {
    background: #fff;
    border-radius: 8px !important;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08); /* 卡片阴影 */
    overflow: hidden;
    margin-bottom: 24px !important;
}

/* 卡片头部 */
.table-header {
    padding: 16px 24px !important;
    border-bottom: 1px solid #E5E6EB; /* 原--gray-200 */
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #F5F7FA; /* 原--gray-100 */
}

.table-title {
    font-size: 16px;
    font-weight: 600;
    color: #1D2129; /* 原--gray-900 */
    margin: 0 !important;
}

/* 2. 时间范围按钮样式 */
.time-btn {
    border-radius: 4px;
    padding: 6px 16px;
    margin-left: 8px;
    font-size: 14px;
    transition: all 0.3s ease; /* 原--transition */
}

.time-btn:hover {
    color: #165DFF; /* 原--primary-color */
    border-color: #165DFF; /* 原--primary-color */
}

.time-btn.active {
    background-color: #165DFF; /* 原--primary-color */
    color: #fff !important;
    border-color: #165DFF; /* 原--primary-color */
}

/* 3. 图表容器样式 */
.data-table .p-4 {
    padding: 24px !important;
}

/* 4. 表格样式优化 */
.table-responsive {
    padding: 0 24px;
}

.table {
    margin-bottom: 0 !important;
    border-collapse: separate;
    border-spacing: 0;
}

.table thead {
    background-color: #F5F7FA; /* 原--gray-100 */
}

.table th {
    padding: 12px 16px !important;
    font-size: 14px;
    font-weight: 600;
    color: #6B7785; /* 原--gray-600 */
    border-bottom: 1px solid #E5E6EB; /* 原--gray-200 */
    text-align: left;
}

.table td {
    padding: 16px !important;
    font-size: 14px;
    color: #1D2129; /* 原--gray-900 */
    border-bottom: 1px solid #E5E6EB; /* 原--gray-200 */
    transition: all 0.3s ease; /* 原--transition */
}

.table tbody tr:hover {
    background-color: #F5F7FA; /* 原--gray-100 */
    cursor: default;
}

/* 调用次数徽章样式 */
.badge {
    padding: 4px 8px;
    font-size: 12px;
    font-weight: 500;
    border-radius: 4px;
}

.badge.bg-primary {
    background-color: #165DFF !important; /* 原--primary-color */
}

.badge.bg-warning {
    background-color: #FAAD14 !important; /* 原--warning-color */
}

.badge.bg-danger {
    background-color: #FF4D4F !important; /* 原--danger-color */
}

/* 5. 详情按钮样式 */
.view-detail {
    border-radius: 4px;
    padding: 4px 12px;
    font-size: 13px;
    color: #165DFF; /* 原--primary-color */
    border-color: #165DFF; /* 原--primary-color */
    transition: all 0.3s ease; /* 原--transition */
}

.view-detail:hover {
    background-color: #165DFF; /* 原--primary-color */
    color: #fff;
}

/* 6. 分页样式优化 */
.pagination-container {
    padding: 16px 24px !important;
    border-top: 1px solid #E5E6EB; /* 原--gray-200 */
}

.pagination-info {
    font-size: 14px;
    color: #6B7785; /* 原--gray-600 */
}

.pagination .btn {
    border-radius: 4px !important;
    padding: 4px 12px;
    margin-left: 4px;
    font-size: 14px;
    color: #6B7785; /* 原--gray-600 */
    border-color: #E5E6EB; /* 原--gray-200 */
    transition: all 0.3s ease; /* 原--transition */
}

.pagination .btn:hover:not(.active):not(:disabled) {
    color: #165DFF; /* 原--primary-color */
    border-color: #165DFF; /* 原--primary-color */
}

.pagination .btn.active {
    background-color: #165DFF; /* 原--primary-color */
    color: #fff;
    border-color: #165DFF; /* 原--primary-color */
}

.pagination .btn:disabled {
    color: #C9CDD4; /* 原--gray-300 */
    border-color: #E5E6EB; /* 原--gray-200 */
    background-color: #fff;
}

/* 7. 搜索框样式 */
.input-group {
    border-radius: 4px;
    overflow: hidden;
}

.form-control {
    border-radius: 4px 0 0 4px !important;
    border-right: none !important;
    font-size: 14px;
    padding: 8px 16px;
}

.form-control:focus {
    border-color: #165DFF; /* 原--primary-color */
    box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.1); /* 原--primary-color透明色 */
}

.clear-search {
    border-radius: 0 !important;
    border-left: none !important;
    color: #6B7785; /* 原--gray-600 */
}

.clear-search:hover {
    color: #FF4D4F; /* 原--danger-color */
    border-color: #E5E6EB; /* 原--gray-200 */
    background-color: #fff;
}

/* 8. 加载状态样式 */
.loading-overlay {
    backdrop-filter: blur(2px);
}

.spinner-border {
    width: 3rem;
    height: 3rem;
    border-width: 0.3rem;
}

/* 9. 空数据提示样式 */
.text-center.py-5 {
    padding: 40px 0 !important;
}

.text-center.py-5 i {
    color: #C9CDD4; /* 原--gray-300 */
    margin-bottom: 12px;
}

.text-center.py-5 p {
    color: #6B7785; /* 原--gray-600 */
    font-size: 14px;
    margin: 0;
}

/* 10. 弹窗样式优化 */
.modal-content {
    border-radius: 8px !important;
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
    border: none;
}

.modal-header {
    padding: 16px 24px;
    border-bottom: 1px solid #E5E6EB; /* 原--gray-200 */
    background-color: #F5F7FA; /* 原--gray-100 */
}

.modal-title {
    font-size: 16px;
    font-weight: 600;
    color: #1D2129; /* 原--gray-900 */
}

.modal-body {
    padding: 24px;
}

.modal-footer {
    padding: 16px 24px;
    border-top: 1px solid #E5E6EB; /* 原--gray-200 */
}

/* 弹窗统计卡片 */
.card.bg-light {
    background-color: #F5F7FA !important; /* 原--gray-100 */
    border: none;
    border-radius: 6px;
    box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.05);
    margin-bottom: 16px;
}

.card-body {
    padding: 16px;
}

.card-title {
    font-size: 14px;
    color: #6B7785; /* 原--gray-600 */
    margin-bottom: 8px;
}

.card-text {
    font-size: 16px;
    font-weight: 600;
    color: #1D2129; /* 原--gray-900 */
    margin: 0;
}

#userDailyTableBody td{
    padding: 10px 16px !important;
}

/* 进度条容器样式 */
.progress-container {
    flex: 1; /* 让进度条容器占据剩余空间 */
    min-width: 100px; /* 确保进度条有足够宽度 */
}

/* 进度条样式调整 */
.progress {
    height: 8px !important;
    border-radius: 4px;
    background-color: #E5E6EB;
    width: 100% !important; /* 确保进度条占满容器 */
    margin: 0 !important;
}

/* 百分比文字样式 */
.percentage-text {
    min-width: 50px; /* 固定百分比文字宽度，确保对齐 */
    text-align: right;
    font-weight: 500;
    color: #1D2129;
}


/* 导出按钮 */
#exportUserData {
    background-color: #165DFF; /* 原--primary-color */
    border-color: #165DFF; /* 原--primary-color */
}

#exportUserData:hover {
    background-color: #0E4BD8; /* 原--primary-color深色调 */
    border-color: #0E4BD8;
}

/* 响应式适配 */
@media (max-width: 992px) {
    .col-lg-8, .col-lg-4 {
        flex: 0 0 100%;
        max-width: 100%;
    }

    .table-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .table-actions {
        margin-top: 12px;
        width: 100%;
        display: flex;
        justify-content: flex-start;
    }

    .time-btn {
        margin-left: 0;
        margin-right: 8px;
    }

    .input-group {
        width: 100% !important;
    }
}
</style>
<!-- 加载提示 -->
<div class="loading-overlay" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.8); z-index: 9999; justify-content: center; align-items: center;">
    <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">加载中...</span>
    </div>
</div>

<!-- 用户详情弹窗 -->
<div class="modal fade" id="userDetailModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">用户【<span id="modalUsername">加载中...</span>】每日调用详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- 加载状态 -->
                <div id="modalLoading" class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </div>

                <!-- 数据统计卡片 -->
                <div id="modalStats" class="d-none mb-1">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h6 class="card-title text-muted">用户ID</h6>
                                    <p class="card-text" id="modalUserId">-</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h6 class="card-title text-muted">总调用天数</h6>
                                    <p class="card-text" id="modalTotalDays">-</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h6 class="card-title text-muted">累计调用次数</h6>
                                    <p class="card-text" id="modalTotalCalls">-</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 图表区域 -->
                <div id="modalChartContainer" class="d-none mb-4" style="height: 180px;">
                    <canvas id="userDailyChart"></canvas>
                </div>

                <!-- 数据表格 -->
                <div id="modalTableContainer" class="d-none">
                    <div class="table-responsive">
                        <table class="table table-hover" style="min-width: auto;">
                            <thead class="table-light">
                                <tr>
                                    <th>日期</th>
                                    <th>调用次数</th>
                                    <th>占比</th>
                                </tr>
                            </thead>
                            <tbody id="userDailyTableBody">
                                <!-- 数据将通过JS动态填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 空数据提示 -->
                <div id="modalEmpty" class="d-none text-center py-5">
                    <i class="fas fa-database text-muted" style="font-size: 2rem;"></i>
                    <p class="mt-2 text-muted">该用户暂无API调用记录</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="exportUserData">导出数据</button>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 每日调用统计图表 -->
    <div class="col-lg-8">
        <div class="data-table">
            <div class="table-header d-flex justify-content-between align-items-center">
                <div class="table-title">每日调用统计</div>
                <div class="table-actions">
                    <button class="btn btn-outline time-btn {% if time_range == 'week' %}active{% endif %}" data-range="week">本周</button>
                    <button class="btn btn-outline time-btn {% if time_range == 'month' %}active{% endif %}" data-range="month">本月</button>
                    <button class="btn btn-outline time-btn {% if time_range == 'year' %}active{% endif %}" data-range="year">全年</button>
                </div>
            </div>
            <div class="p-4">
                <div style="width: 100%; height: 300px;">
                    <canvas id="dailyApiCallChart"></canvas>
                </div>
                <!-- 空数据提示 -->
                {% if not daily_data %}
                <div class="text-center py-5">
                    <i class="fas fa-chart-line text-muted" style="font-size: 2rem;"></i>
                    <p class="mt-2 text-muted">暂无该时间段的API调用数据</p>
                </div>
                {% endif %}
            </div>
        </div>
    </div>

    <!-- 用户调用排行图表 -->
    <div class="col-lg-4">
        <div class="data-table">
            <div class="table-header">
                <div class="table-title">用户调用排行（TOP10）</div>
            </div>
            <div class="p-4">
                <div style="width: 100%; height: 300px;">
                    <canvas id="userApiCallChart"></canvas>
                </div>
                <!-- 空数据提示 -->
                {% if not user_rank_data %}
                <div class="text-center py-5">
                    <i class="fas fa-users text-muted" style="font-size: 2rem;"></i>
                    <p class="mt-2 text-muted">暂无用户API调用数据</p>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- 调用统计详情表格 -->
<div class="data-table mb-1">
    <div class="table-header d-flex justify-content-between align-items-center">
        <div class="table-title">调用统计详情</div>
        <div class="table-actions">
            <form id="searchForm" class="input-group" style="width: 300px;" method="get">
                <!-- 隐藏字段：保留当前时间范围 -->
                <input type="hidden" name="time_range" value="{{ time_range or 'week' }}">
                <input type="text" name="search" class="form-control" placeholder="搜索用户名..."
                       value="{{ search or '' }}">
                <button class="btn btn-primary" type="submit">
                    <i class="fas fa-search"></i>
                </button>
                {% if search %}
                <button type="button" class="btn btn-outline-secondary clear-search">
                    <i class="fas fa-times"></i>
                </button>
                {% endif %}
            </form>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table table-hover">
            <thead class="table-light">
                <tr>
                    <th>ID</th>
                    <th>用户ID</th>
                    <th>用户名</th>
                    <th>调用日期</th>
                    <th>调用次数</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% if data_apicalls %}
                    {% for acg in data_apicalls %}
                    <tr>
                        <td>{{ acg.id }}</td>
                        <td>{{ acg.user_id }}</td>
                        <td>{{ acg.user.username if acg.user and acg.user.username else '未知用户' }}</td>
                        <td>{{ acg.call_date.strftime('%Y-%m-%d') if acg.call_date else '未知日期' }}</td>
                        <td>
                            <span class="badge {% if acg.call_count > 1000 %}bg-danger{% elif acg.call_count > 500 %}bg-warning{% else %}bg-primary{% endif %}">
                                {{ acg.call_count }}
                            </span>
                        </td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary view-detail"
                                    data-id="{{ acg.id }}"
                                    data-userid="{{ acg.user_id }}"
                                    data-username="{{ acg.user.username if acg.user and acg.user.username else '未知用户' }}">
                                <i class="fas fa-eye"></i> 详情
                            </button>
                        </td>
                    </tr>
                    {% endfor %}
                {% else %}
                    <tr>
                        <td colspan="6" class="text-center py-4">
                            <i class="fas fa-database text-muted" style="font-size: 1.5rem;"></i>
                            <p class="mt-2 text-muted">暂无匹配的API调用记录</p>
                        </td>
                    </tr>
                {% endif %}
            </tbody>
        </table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container d-flex justify-content-between align-items-center mt-3">
        <div class="pagination-info">显示 {{ data_apicalls|length }} 条，共 {{ total_apicalls }} 条</div>
        <div class="pagination">
        <!-- 上一页 -->
        <a href="?page={{ page-1 if page > 1 else 1 }}{% if search %}&search={{ search }}{% endif %}"
           class="btn {% if page == 1 %}btn-outline-secondary disabled{% else %} btn-outline-primary{% endif %}">
            <i class="fas fa-chevron-left"></i>
        </a>

        <!-- 分页按钮（修复 max/min 问题） -->
        {% if total_pages > 0 %}
            {% set start_page = (page - 2) if (page - 2) >= 1 else 1 %}
            {% set end_page = (page + 2) if (page + 2) <= total_pages else total_pages %}
            {% for p in range(start_page, end_page + 1) %}
                <a href="?page={{ p }}{% if search %}&search={{ search }}{% endif %}"
                   class="btn btn-outline-primary {% if p == page %}active{% endif %}">{{ p }}</a>
            {% endfor %}
        {% endif %}

        <!-- 下一页 -->
        <a href="?page={{ page+1 if page < total_pages else total_pages }}{% if search %}&search={{ search }}{% endif %}"
           class="btn {% if page == total_pages %}btn-outline-secondary disabled{% else %} btn-outline-primary{% endif %}">
            <i class="fas fa-chevron-right"></i>
        </a>
    </div>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script src="/static/js/chart.js"></script>
<script>
// 从后端接收的数据
const dailyData = {{ daily_data|tojson if daily_data is defined else '[]' }};
const userRankData = {{ user_rank_data|tojson if user_rank_data is defined else '[]' }};
const currentTimeRange = "{{ time_range or 'week' }}";

// 初始化图表实例变量为null，避免未定义错误
window.dailyChartInstance = null;
window.userChartInstance = null;
window.userDailyChart = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化图表
    if (dailyData && dailyData.length > 0) {
        initDailyChart();
    }
    if (userRankData && userRankData.length > 0) {
        initUserRankChart();
    }

    // 绑定时间范围切换事件
    bindTimeRangeEvents();

    // 绑定搜索清空事件
    bindClearSearchEvent();
    bindClearSearchEvent();

    // 绑定详情按钮点击事件
    bindDetailButtonEvents();

    // 绑定导出按钮事件
    document.getElementById('exportUserData').addEventListener('click', exportUserData);
});

// 初始化每日调用图表
function initDailyChart() {
    const ctx = document.getElementById('dailyApiCallChart').getContext('2d');
    // 安全销毁已有图表实例
    if (window.dailyChartInstance && typeof window.dailyChartInstance.destroy === 'function') {
        window.dailyChartInstance.destroy();
    }

    window.dailyChartInstance = new Chart(ctx, {
        type: 'line',
        data: {
            labels: dailyData.map(item => item.date || ''),
            datasets: [{
                label: '调用次数',
                data: dailyData.map(item => item.count || 0),
                borderColor: '#165DFF',
                backgroundColor: 'rgba(22, 93, 255, 0.1)',
                borderWidth: 2,
                tension: 0.3,
                fill: true,
                pointRadius: 4,  // 数据点大小
                pointBackgroundColor: '#165DFF'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        label: function(ctx) {
                            return `调用次数: ${ctx.raw} 次`;
                        }
                    }
                }
            },
            scales: {
                x: {
                    grid: { display: false },
                    ticks: {
                    // 年份数据时，X轴标签旋转45度（避免重叠）
                    maxRotation: dailyData.length === 12 ? 45 : 0,
                    minRotation: 0
                }
                },
                y: { beginAtZero: true, ticks: { precision: 0 } }
            }
        }
    });
}

// 初始化用户排行图表
function initUserRankChart() {
    const ctx = document.getElementById('userApiCallChart').getContext('2d');
    // 安全销毁已有图表实例
    if (window.userChartInstance && typeof window.userChartInstance.destroy === 'function') {
        window.userChartInstance.destroy();
    }

    window.userChartInstance = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: userRankData.map(item => item.username || '未知用户'),
            datasets: [{
                label: '总调用次数',
                data: userRankData.map(item => item.total || 0),
                backgroundColor: '#52C41A',
                borderRadius: 4
            }]
        },
        options: {
            indexAxis: 'y', // 横向柱状图
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: {
                x: { beginAtZero: true, ticks: { precision: 0 } },
                y: { grid: { display: false } }
            }
        }
    });
}

// 绑定时间范围切换事件
function bindTimeRangeEvents() {
    const timeBtns = document.querySelectorAll('.time-btn');
    if (!timeBtns.length) return;

    timeBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const range = this.getAttribute('data-range');
            if (!range || range === currentTimeRange) return;

            // 显示加载提示
            const loadingOverlay = document.querySelector('.loading-overlay');
            if (loadingOverlay) {
                loadingOverlay.style.display = 'flex';
            }

            // 构建跳转URL
            try {
                const urlParams = new URLSearchParams(window.location.search);
                urlParams.set('time_range', range);
                urlParams.set('page', 1); // 切换范围重置到第一页
                window.location.href = '?' + urlParams.toString();
            } catch (e) {
                console.error('处理URL参数错误:', e);
                if (loadingOverlay) {
                    loadingOverlay.style.display = 'none';
                }
            }
        });
    });
}

// 绑定搜索清空事件
function bindClearSearchEvent() {
    const clearBtn = document.querySelector('.clear-search');
    if (!clearBtn) return;

    clearBtn.addEventListener('click', function() {
        const searchInput = document.querySelector('input[name="search"]');
        const searchForm = document.getElementById('searchForm');

        if (searchInput && searchForm) {
            searchInput.value = '';
            searchForm.submit();
        }
    });
}

// 绑定详情按钮事件
function bindDetailButtonEvents() {
    document.querySelectorAll('.view-detail').forEach(btn => {
        btn.addEventListener('click', function() {
            const apicallsId = this.getAttribute('data-id');
            const userId = this.getAttribute('data-userid');
            const username = this.getAttribute('data-username');
            if (userId) {
                openUserDetailModal(userId, apicallsId, username);
            }
        });
    });
}

// 打开用户详情弹窗
function openUserDetailModal(userId, apicallsId, username) {
    // 重置弹窗状态
    const modal = new bootstrap.Modal(document.getElementById('userDetailModal'));
    document.getElementById('modalUsername').textContent = username || '未知用户';
    document.getElementById('modalLoading').classList.remove('d-none');
    document.getElementById('modalStats').classList.add('d-none');
    document.getElementById('modalChartContainer').classList.add('d-none');
    document.getElementById('modalTableContainer').classList.add('d-none');
    document.getElementById('modalEmpty').classList.add('d-none');

    // 显示弹窗
    modal.show();

     //const apiUrl = `/admin/apicalls/user_daily?user_id=${userId}`;
    const apiUrl = `/admin/apicalls/user_daily?apicalls_id=${apicallsId}`;

    fetch(apiUrl)
        .then(response => {
            if (!response.ok) {
                return response.json().then(err => {
                    throw new Error(err.error || `HTTP错误: ${response.status}`);
                }).catch(() => {
                    throw new Error(`HTTP错误: ${response.status}`);
                });
            }
            return response.json();
        })
        .then(data => {
            if (data.success && data.data) {
                renderUserDetail(data.data);
            } else {
                document.getElementById('modalLoading').classList.add('d-none');
                document.getElementById('modalEmpty').classList.remove('d-none');
                document.querySelector('#modalEmpty p').textContent = data.error || '未找到用户数据';
            }
        })
        .catch(error => {
            console.error('加载用户详情失败:', error);
            document.getElementById('modalLoading').classList.add('d-none');
            document.getElementById('modalEmpty').classList.remove('d-none');

            let errorMsg = '加载失败，请重试';
            if (error.message.includes('404')) {
                errorMsg = '接口不存在，请检查配置';
            } else if (error.message.includes('403')) {
                errorMsg = '没有权限访问，请重新登录';
            } else if (error.message.includes('500')) {
                errorMsg = '服务器内部错误，请稍后重试';
            } else if (error.message.includes('Failed to fetch')) {
                errorMsg = '网络连接失败，请检查网络';
            }

            document.querySelector('#modalEmpty p').textContent = errorMsg;
        });
}

// 渲染用户详情数据
function renderUserDetail(data) {
    // 隐藏加载状态
    document.getElementById('modalLoading').classList.add('d-none');
    // 显示统计信息
    document.getElementById('modalUserId').textContent = data.user_id || '-';
    document.getElementById('modalTotalDays').textContent = data.total_days || '0';
    document.getElementById('modalTotalCalls').textContent = data.total_calls || '0';
    document.getElementById('modalStats').classList.remove('d-none');

    // 如果有数据，渲染图表和表格
    if (data.daily_records && data.daily_records.length > 0) {
        // 渲染表格
        renderUserDailyTable(data.daily_records, data.total_calls || 0);

        // 渲染图表
        renderUserDailyChart(data.daily_records);

        // 显示图表和表格
        document.getElementById('modalChartContainer').classList.remove('d-none');
        document.getElementById('modalTableContainer').classList.remove('d-none');

        // 存储数据用于导出
        window.currentUserData = data;
    } else {
        // 显示空数据提示
        document.getElementById('modalEmpty').classList.remove('d-none');
    }
}

// 渲染用户每日调用表格
function renderUserDailyTable(records, totalCalls) {
    const tableBody = document.getElementById('userDailyTableBody');
    tableBody.innerHTML = '';

    // 按日期升序排列
    const sortedRecords = [...records].sort((a, b) => new Date(a.date) - new Date(b.date));

    sortedRecords.forEach(record => {
        // 计算占比
        const percentage = totalCalls > 0 ? ((record.calls / totalCalls) * 100).toFixed(1) : '0.0';

        // 修改后
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${record.date}</td>
            <td>${record.calls}</td>
            <td>
                        <!-- 外层 Flex 容器：控制进度条和文本在同一行 -->
                        <div class="d-flex align-items-center gap-2">
                            <!-- 进度条容器：占满剩余空间 -->
                            <div class="progress-container flex-grow-1">
                                <div class="progress" style="height: 18px;"> <!-- 可选：调整进度条高度 -->
                                    <div class="progress-bar bg-primary"
                                         role="progressbar"
                                         style="width: ${percentage}%"
                                         aria-valuenow="${percentage}"
                                         aria-valuemin="0"
                                         aria-valuemax="100">
                                    </div>
                                </div>
                            </div>
                            <!-- 百分比文本：固定宽度，避免挤压 -->
                            <span class="percentage-text" style="width: 50px; text-align: right;">${percentage}%</span>
                        </div>
                    </td>
        `;
        tableBody.appendChild(tr);
    });
}

// 渲染用户每日调用图表
function renderUserDailyChart(records) {
    const ctx = document.getElementById('userDailyChart').getContext('2d');

    // 安全销毁已有图表实例（核心修复）
    if (window.userDailyChart && typeof window.userDailyChart.destroy === 'function') {
        window.userDailyChart.destroy();
    }

    // 按日期排序
    const sortedRecords = [...records].sort((a, b) => new Date(a.date) - new Date(b.date));

    window.userDailyChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: sortedRecords.map(item => item.date),
            datasets: [{
                label: '每日调用次数',
                data: sortedRecords.map(item => item.calls),
                backgroundColor: 'rgba(22, 93, 255, 0.7)',
                borderRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        label: function(ctx) {
                            return `调用次数: ${ctx.raw} 次`;
                        }
                    }
                }
            },
            scales: {
                x: {
                    grid: { display: false }
                },
                y: {
                    beginAtZero: true,
                    ticks: { precision: 0 }
                }
            }
        }
    });
}

// 导出用户数据
function exportUserData() {
    if (!window.currentUserData) return;

    const data = window.currentUserData;
    // 构建CSV内容
    let csvContent = "日期,调用次数\n";
    data.daily_records.forEach(record => {
        csvContent += `${record.date},${record.calls}\n`;
    });

    // 创建下载链接
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', `用户${data.user_id}_${data.username}_调用记录.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
</script>
{% endblock %}